package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.atguigu.lease.common.uilt.PageUtil.getPage;


@Tag(name = "公寓信息管理")
@RestController
@RequestMapping("/admin/apartment")
public class ApartmentController {

    @Autowired
    private ApartmentInfoService apartmentInfoService;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private RoomInfoService roomInfoService;


    @Operation(summary = "保存或更新公寓信息")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody ApartmentSubmitVo apartmentSubmitVo) {

        Long apartmentSubmitVoId = apartmentSubmitVo.getId();
        if (null != apartmentSubmitVoId){
            // 删除旧的关系数据
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                    .eq(ApartmentFacility::getApartmentId,apartmentSubmitVoId)
            );
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                    .eq(ApartmentLabel::getApartmentId,apartmentSubmitVoId)
            );
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                    .eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVoId)
            );
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>()
                    .eq(GraphInfo::getItemId,apartmentSubmitVoId)
                    .eq(GraphInfo::getItemType,ItemType.APARTMENT)
            );
        }
            // 1. save ApartmentSubmitVo --> sava()执行完，会将自增主键值回填给 apartmentSubmitVo id
            apartmentInfoService.saveOrUpdate(apartmentSubmitVo);
            // 2 save apartmentFacility (公寓-配套)关系
            // stream 实现
            List<ApartmentFacility> apartmentFacilityList = apartmentSubmitVo.getFacilityInfoIds().stream().map(fid -> {
                return ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId()).facilityId(fid).build();
            }).collect(Collectors.toList());
            apartmentFacilityService.saveOrUpdateBatch(apartmentFacilityList);

            // 3 save ApartmentLabel (公寓-标签)关系
            List<ApartmentLabel> apartmentLabelList = apartmentSubmitVo.getLabelIds().stream().map(lid -> {
                return ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(lid).build();
            }).collect(Collectors.toList());
            apartmentLabelService.saveOrUpdateBatch(apartmentLabelList);


            // 4 save ApartmentFeeValue (公寓-杂费)关系
            List<ApartmentFeeValue> apartmentFeeValueList = apartmentSubmitVo.getFeeValueIds().stream()
                    .map(feeValueId -> ApartmentFeeValue.builder().apartmentId(apartmentSubmitVo.getId())
                            .feeValueId(feeValueId).build()).collect(Collectors.toList());
            apartmentFeeValueService.saveOrUpdateBatch(apartmentFeeValueList);

            // 5 save GraphInfo 上传图片
            apartmentSubmitVo.getGraphVoList().forEach(graphVo -> {
                GraphInfo graphInfo = new GraphInfo();
                BeanUtils.copyProperties(graphVo,graphInfo);
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoService.saveOrUpdate(graphInfo);
            });

        return Result.ok();
    }

/*    @Operation(summary = "根据条件分页查询公寓列表")
    @GetMapping("pageItem")
    public Result<IPage<ApartmentItemVo>> pageItem(@RequestParam long current, @RequestParam long size, ApartmentQueryVo queryVo) {
        Page<ApartmentItemVo> page = Page.of(current, size);
        IPage<ApartmentItemVo> apartmentItemVoIPage = apartmentInfoService.pageApartmentItemByQuery(page, queryVo);
        return Result.ok(apartmentItemVoIPage);
    }*/

    @Operation(summary = "根据条件分页查询公寓列表")
    @GetMapping("pageItem")
    public Result<IPage<ApartmentItemVo>> pageItem(HttpServletRequest request, ApartmentQueryVo queryVo) {
        Page<ApartmentItemVo> page = getPage(request);
        IPage<ApartmentItemVo> apartmentItemVoIPage = apartmentInfoService.pageApartmentItemByQuery(page, queryVo);
        return Result.ok(apartmentItemVoIPage);
    }


    @Operation(summary = "根据ID获取公寓详细信息")
    @GetMapping("getDetailById")
    public Result<ApartmentDetailVo> getDetailById(@RequestParam Long id) {
        ApartmentDetailVo apartmentDetailVo = apartmentInfoService.getApartmentDetailVoById(id);
        return Result.ok(apartmentDetailVo);
    }

    @Operation(summary = "根据id删除公寓信息")
    @DeleteMapping("removeById")
    public Result removeById(@RequestParam Long id) {
        if (roomInfoService.roomCountByApartmentId(id) > 0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        // remove apartmentInfo
        apartmentInfoService.removeById(id);
        // 删除对应关系
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,id));
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,id));
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType,ItemType.APARTMENT));
        return Result.ok();
    }

    @Operation(summary = "根据id修改公寓发布状态")
    @PostMapping("updateReleaseStatusById")
    public Result updateReleaseStatusById(@RequestParam Long id, @RequestParam ReleaseStatus status) {
        apartmentInfoService.update(new LambdaUpdateWrapper<ApartmentInfo>().set(ApartmentInfo::getIsRelease,status).eq(ApartmentInfo::getId,id));
        return Result.ok();
    }

    @Operation(summary = "根据区县id查询公寓信息列表")
    @GetMapping("listInfoByDistrictId")
    public Result<List<ApartmentInfo>> listInfoByDistrictId(@RequestParam Long id) {
        List<ApartmentInfo> apartmentInfos = apartmentInfoService.list(new LambdaQueryWrapper<ApartmentInfo>().eq(ApartmentInfo::getDistrictId, id));
        return Result.ok(apartmentInfos);
    }
}














